package com.hifar.test.equipsensor.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.hifar.common.QueryParamBean;
import com.hifar.test.equipsensor.pojo.EquipClassifySearchVo;
import com.hifar.test.equipsensor.pojo.EquipSensorSearchVo;
import com.hifar.test.equipsensor.pojo.HfResEquipSensor;
import com.hifar.test.equipsensor.pojo.VO.HfResEquipSensorAddVO;
import com.hifar.test.equipsensor.pojo.VO.HfResEquipSensorQueryParamVo;
import com.hifar.test.equipsensor.service.IHfResEquipSensorService;
import com.hifar.test.sensor.pojo.HfResSensor;
import com.hifar.test.sensor.service.IHfResSensorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.PageResult;
import com.hifar.sys.RequestConver;
import com.hifar.sys.SystemLoginUser;
import com.hifar.sys.SystemUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 资源-设备传感器-关系表 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-11 14:13:02
 */
@RestController
@RequestMapping("/api/busi/test/hfResEquipSensorController")
@Api(tags = "资源-设备传感器-关系表功能")
public class HfResEquipSensorController {

    @Autowired
    private IHfResEquipSensorService hfResEquipSensorService;

    @Autowired
    private IHfResSensorService hfResSensorService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @PostMapping(value = "/listPageEquipSensorSearchVo")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listPageEquipSensorSearchVo(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<EquipSensorSearchVo> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));
        queryWrapper.eq("equip_id", equipId);
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<EquipSensorSearchVo> page = new Page<>((Integer) pageInfo.get("pageNo"),
                    (Integer) pageInfo.get("pageSize"));
            Page<EquipSensorSearchVo> page1 = hfResEquipSensorService.entityVoPage(page, queryWrapper);
            page1.getRecords().forEach(item -> {
            });
            /* 计算分页信息返回给前端 */
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listEquipClassifySearchVo")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listEquipClassifySearchVo(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            pageInfo = new HashMap<String, Object>();
        }
        QueryWrapper<EquipClassifySearchVo> queryWrapper = RequestConver.getPostParam(pageInfo);

        List<EquipClassifySearchVo> dataList = hfResEquipSensorService.listEntityEquipClassifyVo(queryWrapper);
        if (dataList != null) {
            return BusiResponse.OK(dataList);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/list")
    @ApiOperation(value = "资源-设备传感器-关系表功能:分页查询列表")
    public BusiResponse list(@RequestBody @Validated HfResEquipSensorQueryParamVo queryParamVo) {

        QueryParamBean queryParamBean = new QueryParamBean<>(queryParamVo);
        queryParamBean.addColumns(HfResSensor.class, "s");
        QueryWrapper queryWrapper = queryParamBean.getQueryWrapper();
        List<String> excludeIdList = Optional.ofNullable(queryParamVo.getExcludeIdList()).orElse(new ArrayList<>());

        String equipId = queryParamVo.getEquipId();
        queryWrapper.notIn(!excludeIdList.isEmpty(), "t.id", excludeIdList);
        queryWrapper.eq("t.equip_id", equipId);
        queryWrapper.ne("t.del_flag", 1);
        queryWrapper.in("s.secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.orderByDesc("t.create_time");
        Page page = queryParamBean.getPage();
        Page<EquipSensorSearchVo> pageData = hfResEquipSensorService.entityVoPage(page, queryWrapper);
        /* 计算分页信息返回给前端 */
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "资源-设备传感器-关系表功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<EquipSensorSearchVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));
        queryWrapper.eq("equip_id", equipId);
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);

        List<EquipSensorSearchVo> list = hfResEquipSensorService.listEntityVo(queryWrapper);
        list.forEach(item -> {
        });
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "资源-设备传感器-关系表功能:新增")
    public BusiResponse add(@RequestBody @Validated HfResEquipSensorAddVO sensorAddVO) {
        String equipId = sensorAddVO.getEquipId();
        List<String> sensorIdList = sensorAddVO.getSensorIdList();
        List<HfResEquipSensor> equipSensorList = new ArrayList<>();
        for (String sensorId : sensorIdList) {
            HfResEquipSensor hfResEquipSensor = new HfResEquipSensor();
            hfResEquipSensor.setEquipId(equipId);
            hfResEquipSensor.setSensorId(sensorId);
            equipSensorList.add(hfResEquipSensor);
        }
        hfResEquipSensorService.saveBatch(equipSensorList);
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "资源-设备传感器-关系表功能:编辑")
    public BusiResponse edit(@RequestBody HfResEquipSensor hfResEquipSensor) {
        hfResEquipSensorService.updateById(hfResEquipSensor);
        return BusiResponse.ok("编辑成功！");
    }

    @GetMapping("/queryById")
    @ApiOperation(value = "资源-设备传感器-关系表功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id) {
        // HfResEquipSensor byId = hfResEquipSensorService.getById(id);

        QueryWrapper<EquipSensorSearchVo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("id", id);
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);

        List<EquipSensorSearchVo> list = hfResEquipSensorService.listEntityVo(queryWrapper);
        if (list != null && list.size() > 0) {
            // 查询转换附件
            return BusiResponse.OK(list.get(0));
        } else {
            return BusiResponse.error(400, "未查询到数据！");
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "资源-设备传感器-关系表功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        QueryWrapper<HfResEquipSensor> delete = new QueryWrapper<>();
        delete.in("id", idList);
        hfResEquipSensorService.remove(delete);
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "资源-设备传感器-关系表功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfResEquipSensorService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("资源-设备传感器-关系表.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "资源-设备传感器-关系表功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                return hfResEquipSensorService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }

}